/**
 * 初始化整体流量图标
 */
define(function(){
     var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');

    var zrUtil = require('zrender/tool/util');
    var zrnumber = require('echarts/util/number');
    var myChart = ec.init(document.getElementById('total'));
     var option_day = {
         tooltip : {
             trigger: 'axis',
             formatter:function(params, ticket, callback){
                 var date_current=params[0][1];
                 var data_current=params[0][2];
                 var index_current=getIndexByName(option_day.xAxis[0].data,date_current);
                 var data_day="-",data_week="-",data_month="-",data_month2="-";
                 var day_td='<td></td>';
                 if(index_current-1>=0){
                     data_day= option_day.series[0].data[index_current-1];
                     var s=(((data_current/data_day)-1)*100).toFixed(2);
                     if(s>0){
                         day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                     }else{
                         day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                     }
                 }
                 var week_td='<td></td>';
                 if(index_current-7>=0){
                     data_week= option_day.series[0].data[index_current-7];
                     var s=(((data_current/data_week)-1)*100).toFixed(2);
                     if(s>0){
                         week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                     }else{
                         week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                     }
                 }
                 var month_td='<td></td>';
                 if(index_current-28>=0){
                     data_month= option_day.series[0].data[index_current-28];
                     var s=(((data_current/data_month)-1)*100).toFixed(2);
                     if(s>0){
                         month_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                     }else{
                         month_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                     }
                 }
                 var month_td2='<td></td>';
                 if(isMonth()&&index_current-12>=0){
                     data_month2= option_day.series[0].data[index_current-12];
                     var s=(((data_current/data_month2)-1)*100).toFixed(2);
                     if(s>0){
                         month_td2='<td style="color:orangered;">'+s+'%&#8593</td>';
                     }else{
                         month_td2='<td style="color:greenyellow;">'+s+'%&#8595</td>';
                     }
                 }
                 var dateVal = formatShowDate(date_current);
                 var result='<table class="table-center">' +
                     '<tr><td>'+dateVal+'</td><td>'+zrnumber.addCommas(data_current)+'</td><td></td><td>';
                if(isDay())
                     result += getWeekDay(dateVal);
                 result += '</td></tr>';
                 if(isWeek()){
                     result+= '<tr><td>前一周</td><td>'+zrnumber.addCommas(data_day)+'</td><td>周环比</td>'+day_td+'</tr>';
                 }else if(isMonth()){
                     result+='<tr><td>前一月</td><td>'+zrnumber.addCommas(data_day)+'</td><td>月环比</td>'+day_td+'</tr>';
                     result+='<tr><td>去年同月</td><td>'+zrnumber.addCommas(data_month2)+'</td><td>月同比</td>'+month_td2+'</tr>';

                 }else{
                     result+='<tr><td>前一日</td><td>'+zrnumber.addCommas(data_day)+'</td><td>日环比</td>'+day_td+'</tr>';
                     result+= '<tr><td>前一周</td><td>'+zrnumber.addCommas(data_week)+'</td><td>周同比</td>'+week_td+'</tr>';
                     result+='<tr><td>前一月</td><td>'+zrnumber.addCommas(data_month)+'</td><td>月同比</td>'+month_td+'</tr>';
                 }
                 result+='</table>';
                 return   result;
             }
         },
         toolbox: {
             show : true,
             orient:'vertical',
             feature : {
                 mark : {show: true},
                 dataZoom : {show: true},
                 magicType : {show: true, type: ['line','bar']},
                 restore : {show: true},
                 saveAsImage : {show: true}
             }
         },
            xAxis: [{
                type: "category",
                 boundaryGap: true,
                data:[''],
                axisLabel:{formatter:function(value){
                    return value.substr(0,4)+"-"+value.substr(4,2)+"-"+value.substr(6,2);
                }}
            }],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: 'series1',
                    type: 'line',
                    smooth: true,
                    symbol:'none',
                    data:[]
                }
            ]
        };

    /**
     * 根据指标显示日数据
     * @param eventType 事件类型0,不变； 1 修改坐标缩放，2 不修改坐标缩放,但显示
     * eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    function show(cate,eventType){
        var dateGrp = $('#totalOption').attr('dateGrp');
        var indexType = $('#totalOption').attr('indexType');
        myChart.showLoading({
            text: '正在努力的读取数据中...'
        });

        $.ajax({
              url: '/dashboard/dashboard/netflow/ajax/' + cate + '/' + indexType,
              type: 'POST',
              async: true,
              data:{"dateGroup":dateGrp},
              dataType: 'json',
              success: function(data, textStatus) {
                          option_day.xAxis[0].data = data.time;
                          option_day.series[0].data = data.data;
                          option_day.series[0].name=cate;
                          //区域缩放重置
                          var datezoom_local={
                            stat_date:{start:(1-31/data.time.length)*100,end:100},
                            week_begin:{start:(1-12/data.time.length)*100,end:100},
                            month_num:{start:0,end:100},
                        };
                        if(data.time.length<31){
                            datezoom_local={
                                stat_date:{start:0,end:100},
                                week_begin:{start:0,end:100},
                                month_num:{start:0,end:100},
                            };
                        }

                        if(eventType == 1 || eventType == 2){
                            if('stat_date'==dateGrp){
                              	option_day.series[0].type='line';                       
                                  option_day.xAxis[0].axisLabel.formatter=function(value){
                                      return value.substr(0,4)+"-"+value.substr(4,2)+"-"+value.substr(6,2);
                                  }
                            }else if('week_begin'==dateGrp){
                                option_day.series[0].type='bar';
                                option_day.xAxis[0].axisLabel.formatter=function(value){
                                      return value;
                                }
                            }else if('month_num'==dateGrp){
                                  option_day.series[0].type='bar';
                                  option_day.xAxis[0].axisLabel.formatter=function(value){
                                      return value.substr(0,4)+"年"+value.substr(4,2)+"月";
                                  }
                            }
                            if(eventType == 1 && myChart.component.dataZoom){
                                option_day.dataZoom=datezoom_local[dateGrp];
                                myChart.component.dataZoom.absoluteZoom(datezoom_local[dateGrp]);
                                 option_day.dataZoom.show=true;
                            }else if(eventType == 2){
                                option_day.dataZoom=datezoom_local[dateGrp];
                                option_day.dataZoom.show=!$('#time_checkbox_total').is(":checked");
                            }
                            myChart.setOption(option_day,true);
                            myChart.refresh();
                        }else if(eventType == 0){
                            myChart.component.dataZoom=compDataZoom_old;
                            // option_day.dataZoom.show=true;
                            myChart.setOption(option_day,true);
                            if($('#time_input_total').val()){
                                EC.addCompare($('#time_input_total').val());
                            }
                         }

                    // myChart.clear();
                    myChart.hideLoading();
                    },
              error : function() {
                  myChart.hideLoading();
              	}
        });
    }


    function getShowDays(){
        // myChart.component.dataZoom=compDataZoom_old;
        // console.log("-------dataZoom------");
        // console.log(myChart.component.dataZoom.option.xAxis[0].data);
        // console.log("----compDataZoom_old----");
        // console.log(compDataZoom_old.option.xAxis[0].data);
        return compDataZoom_old.option.xAxis[0].data;
    }

    function addCompare(time){
         time=formatTime(time);
        var copy=zrUtil.clone(option_day);
         copy.toolbox.feature.magicType.show=false;
        copy.toolbox.feature.dataZoom.show=false;
        var index_time=getIndexByName(option_day.xAxis[0].data,time);
        var showDays = getShowDays();
        var index_show=getIndexByName(option_day.xAxis[0].data,showDays[0]);
        var length=showDays.length;
        setCompareXaxis(copy,index_time,index_show,length);
        setCompareSeries(copy,index_time,index_show,length);
        setCompareLegend(copy);
        setCompareTooltip(copy);
        delete copy.dataZoom;
        myChart.restore();
        myChart.setOption(copy,true);
    }

    function setCompareTooltip(copy){
        copy.series[1]&&copy.series[1].tooltip&&(copy.series[1].tooltip={show:false});
        copy.series[2]&&copy.series[2].tooltip&&(copy.series[2].tooltip={show:false});
        copy.series[3]&&copy.series[3].tooltip&&(copy.series[3].tooltip={show:false});

        copy.tooltip.formatter=function(params, ticket, callback){
            var date_current=params[0][1];
            var data_current=params[0][2];
            var index_current=getIndexByName(copy.xAxis[0].data,date_current);

            var dateVal = formatShowDate(date_current);
            var result='<table class="table-center">' +
                '<tr><td>'+dateVal;
            //是日要显示周几
            if(isDay())
                 result += ' ('+getWeekDay(dateVal)+')';
            result += '</td><td>'+zrnumber.addCommas(data_current)+'</td></tr>';
            if(copy.series[1]){
                var data_compare=copy.series[1].data[index_current];
                var s=(((data_current-data_compare)/data_compare)*100).toFixed(2);
                dateVal = formatShowDate(copy.xAxis[1].data[index_current]);
                result+='<tr><td>'+dateVal;
                if(isDay())
                    result += ' ('+getWeekDay(dateVal)+')';
                result += '</td><td>'+zrnumber.addCommas(data_compare)+'</td></tr>';
                if(s>0){
                    result+='<tr><td>变化</td><td style="color: orangered">'+s+'%&#8593</td></tr>';
                }else{
                    result+='<tr><td>变化</td><td style="color: greenyellow">'+s+'%&#8595</td></tr>';
                }
            }
            result+='</table>';
            return   result;
        }
    }

    function setCompareLegend(copy){
        copy.legend= {
            data:[copy.series[0].name, copy.series[1].name],
            selectedMode:false
        }
    }

    function formatTime(time){
        return time.replace(/\-/g,'')
    }

    function removeCompare(){
        option_day.dataZoom.show=true;
        myChart.component.dataZoom=compDataZoom_old;
        myChart.setOption(option_day,true);
    }

    function  setCompareSeries(copy,index_time,index_show,length){
        copy.series=[];
        //原来数据
        copy.series.push(zrUtil.clone(option_day.series[0]));
        copy.series[0].type='line';
        copy.series[0].data=option_day.series[0].data.slice(index_show,index_show+length);
        //对比数据
        copy.series.push(zrUtil.clone(option_day.series[0]));
        copy.series[1].type='line';
        copy.series[1].name="对比时间段";
        copy.series[1].xAxisIndex=1;
        copy.series[1].data=option_day.series[0].data.slice(index_time,index_time+length);
        if(length>31){return}
        //对比柱
        copy.series.push({
            tooltip:{show:false},
            show:false,
            name: '对比时间段1',
            type: 'bar',
            stack: '1',
            barWidth:3,
            xAxisIndex:1,
            itemStyle:{
                normal:{
                    color:'rgba(0,0,0,0)'
                },
                emphasis:{
                    color:'rgba(0,0,0,0)'
                }
            },
            data: function(){
                var i=0;
               return $.map(copy.series[1].data,function(val){
                   var tt=copy.series[0].data[i++];
                   if(val<tt){
                       return val;
                   }else{
                       return tt;
                   }
                })
            }()
        });
        copy.series.push({
            tooltip:{show:false},
            name: '变化',
            type: 'bar',
            stack: '1',
            xAxisIndex:1,
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(val<tt){
                        return tt-val;
                    }else{
                        return {value : val-tt, itemStyle:{ normal:{color:'red'}}};
                        //return val-tt;
                    }
                })
            }()
        });
    }

    /**
     * 设置对比的xaxis
     */
    function setCompareXaxis(copy,index_time,index_show,length){
        copy.xAxis=[];
        copy.xAxis.push(zrUtil.clone(option_day.xAxis[0]));
        copy.xAxis.push(zrUtil.clone(option_day.xAxis[0]));
        copy.xAxis[0].data=option_day.xAxis[0].data.slice(index_show,index_show+length);
        copy.xAxis[1].data=option_day.xAxis[0].data.slice(index_time,index_time+length);
    }

    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
}

    function isDay(){
        var dateGrp = $('#totalOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return true;
        }
        return false;
    }


    function isWeek(){
        var dateGrp = $('#totalOption').attr('dateGrp');
        if('week_begin'==dateGrp){
            return true;
        }
        return false;
    }

    function isMonth(){
        var dateGrp = $('#totalOption').attr('dateGrp');
        if('month_num'==dateGrp){
            return true;
        }
        return false;
    }

    function formatShowDate(yyyymmdd){
        var dateGrp = $('#totalOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return yyyymmdd.substr(0,4)+"-"+yyyymmdd.substr(4,2)+"-"+yyyymmdd.substr(6,2);
        }else if('week_begin'==dateGrp){
            return yyyymmdd;
        }else if('month_num'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
}


    function getAllDays(){
        return option_day.xAxis.data||option_day.xAxis[0].data;
    }
    
        /**
     * 根据指标显示周数据
     * @param index
     */
    function showWeek(cate,index){

    }
    /**
     * 根据指标显示月数据
     * @param index
     */
    function showMonth(cate,index){

    }
    var compDataZoom_old;
    function hideDataZoom(){
        compDataZoom_old=myChart.component.dataZoom;
        option_day.dataZoom.show=false;
        myChart.setOption(option_day,false);
    }


    var EC={
        echart:myChart,
        show:show,
        getShowDays:getShowDays,
        getAllDays:getAllDays,
        hideDataZoom:hideDataZoom,
        addCompare:addCompare,
        removeCompare:removeCompare
    };

    //指标选择事件
    $("#index_total").change(function(){
        changeIndex(this);
        var type = 2;
        if($('#time_checkbox_total').is(":checked"))
            type=0;
        EC.show(cate,type);
    });

    //日周月切换事件
    $(":button.btnTotal[dateGrp]").click(function(){
        changeDateGrp(this);
        $('#time_checkbox_total').attr('checked',false);
        $('#time_input_total').val('');
        $('#time_input_total').attr('disabled','');
        if($(this).attr('dateGrp')=='week_begin'){
            $('#time_input_total').parent().hide();
        }else{
            $('#time_input_total').parent().show()
        }
        EC.show(cate,1);
    });
    //时间勾选框事件
    $('#time_checkbox_total').change(function(e){
        var input=$('#time_input_total');
        if(!input)return;
        if($(this).is(":checked")){
            input.removeAttr('disabled');
            input.attr('placeholder','选择比较时间起点');
            EC.hideDataZoom();
            setDatePicker(EC, $('#totalOption').attr('dateGrp'),input);
        }else{  
            input.val('');
            input.attr('disabled','');
            input.attr('placeholder','添加对比');       
            EC.removeCompare();
        }
    });
    //时间选择事件
    $('#time_input_total').datepicker().on('changeDate',function(e){
        EC.addCompare(e.format());
    });

    return EC;
});

